#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <cerrno>
#include <functional>
#include <unordered_map>
#include "Log.hpp"
#include "nocopy.hpp"
#include "epoller.hpp"
#include "Socket.hpp"
#include "EventLoop.hpp"
class Listener
{
public:
    // 链接管理器
    void Accepter(std::weak_ptr<Connection> conn)
    {
        auto connection = conn.lock();
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sock = ::accept(connection->FdSock(), (sockaddr *)&peer, &len);
            if (sock > 0)
            {
                uint16_t peerport = ntohs(peer.sin_port);
                char ipbuf[128];
                inet_ntop(AF_INET, &peer.sin_addr.s_addr, ipbuf, sizeof(ipbuf));
                lg(Debug, "get a new client, get info-> [%s:%d], sockfd : %d", ipbuf, peerport, sock);
                SetNonBlockOrDie(sock);
                // AddConnection(sock, EPOLLIN, std::bind(&TcpServer::Recver, this, std::placeholders::_1),
                //               std::bind(&TcpServer::Sender, this, std::placeholders::_1),
                //               std::bind(&TcpServer::Excepter, this, std::placeholders::_1), ipbuf, peerport);
            }
            else
            {
                if (errno == EWOULDBLOCK)
                    break;
                else if (errno == EINTR)
                    continue;
                else
                    break;
            }
        }
    }
    std::shared_ptr<Sock> _listensock_ptr; // 监听socket， 可以把他移除到外部
};